package wfm.activiti;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.activiti.engine.HistoryService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.history.HistoricVariableInstanceQuery;
import org.activiti.engine.impl.el.Expression;

import wfm.entities.Ticket;
import wfm.query.QueryDao;

public class PredictionBehavior implements JavaDelegate
{
	
	@Override
	public void execute(DelegateExecution execution) throws Exception 
	{
		
		System.out.println("validationbehaviours");
		
		Ticket ticket = (Ticket)QueryDao.getVariableToProcessById(execution.getProcessInstanceId(), "ticket");
		
		try
		{
			
			List<HistoricVariableInstance> instances = QueryDao.getAllHistoricVariableInstances("ticket");
			
			int count = 0;
			
			for(HistoricVariableInstance instance : instances){
				try{
					Ticket t = (Ticket)instance.getValue();
					
					if(t.getId() != ticket.getId() && t.getCustomer().getAddress().equals(ticket.getCustomer().getAddress()) ){
						count++;
					}
				}catch (Throwable t){
//					System.out.println("not serializable - old case");
				}
			}
			
			String predFault="There were "+count+" prediction faults in this property!";
			
			execution.setVariable("predFault", predFault);
		}
		catch(Throwable t){
			FacesContext fc = FacesContext.getCurrentInstance();
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Problem with Prediction Analyses!!!", null);
		    fc.addMessage(null, msg);
		    fc.renderResponse();
		}
		
	}
}
